package com.wp.admin.service.impl;

import com.wp.admin.mapper.SysMenuMapper;
import com.wp.admin.pojo.SysMenu;
import com.wp.admin.service.SysMenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author wp
 * @create 2019-03-03 15:48
 */
@Service
@Transactional
public class SysMenuServiceImpl implements SysMenuService {

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    public List<SysMenu> findByUserName(String userName) {
        if (StringUtils.isBlank(userName)) {
            return sysMenuMapper.selectAll();
        }
        return sysMenuMapper.findByUserName(userName);
    }

    @Override
    public List<SysMenu> findTree(String userName, Integer menuType) {
        List<SysMenu> userMenus = findByUserName(userName);
        List<SysMenu> parentMenus = userMenus.stream().filter(menu -> menu.getParentId() == null || menu.getParentId() == 0).collect(Collectors.toList());
        parentMenus.forEach(menu -> menu.setLevel(0));
        parentMenus.sort((m1, m2) -> m1.getOrderNum().compareTo(m2.getOrderNum()));
        findChildren(parentMenus, userMenus, menuType);
        return parentMenus;
    }

    private void findChildren(List<SysMenu> parentMenus, List<SysMenu> userMenus, Integer menuType) {
        for (SysMenu parentMenu : parentMenus) {
            if (menuType == 1) {
                userMenus = userMenus.stream().filter(menu -> menu.getType() != 2).collect(Collectors.toList());
            }
            List<SysMenu> childrenMenus = userMenus.stream().filter(menu -> menu.getId() != null && parentMenu.getId().equals(menu.getParentId())).collect(Collectors.toList());
            childrenMenus.forEach(menu -> {
                menu.setParentName(parentMenu.getName());
                menu.setLevel(parentMenu.getLevel() + 1);
            });
            childrenMenus.sort((m1, m2) -> m1.getOrderNum().compareTo(m2.getOrderNum()));
            parentMenu.setChildren(childrenMenus);
            findChildren(childrenMenus, userMenus, menuType);
        }
    }
}
